/*
	Adobe Systems Incorporated(r) Source Code License Agreement
	Copyright(c) 2007 Adobe Systems Incorporated. All rights reserved.
	
	Please read this Source Code License Agreement carefully before using
	the source code.
	
	Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, 
	no-charge, royalty-free, irrevocable copyright license, to reproduce,
	prepare derivative works of, publicly display, publicly perform, and
	distribute this source code and such derivative works in source or 
	object code form without any attribution requirements.  
	
	The name "Adobe Systems Incorporated" must not be used to endorse or promote products
	derived from the source code without prior written permission.
	
	You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and
	against any loss, damage, claims or lawsuits, including attorney's 
	fees that arise or result from your use or distribution of the source 
	code.
	
	THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT 
	ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  ALSO, THERE IS NO WARRANTY OF 
	NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT.  IN NO EVENT SHALL ADOBE
	OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
	OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
	WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
	OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF
	ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.adobe.apps.ascension.importers
{
	import com.adobe.apps.ascension.Song;
	import mx.collections.ArrayCollection;
	import com.adobe.utils.XMLUtil;
	import com.adobe.utils.ArrayUtil;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	import flash.events.IOErrorEvent;
	import com.adobe.apps.ascension.events.ImportProgressEvent;
	import com.adobe.apps.ascension.events.ImportEvent;
	import flash.system.Capabilities;
	import flash.events.ProgressEvent;
	import com.adobe.apps.ascension.events.ImportParseErrorEvent;
	import flash.xml.XMLNode;
	
	[Event(name="progress", type="flash.events.ProgressEvent")]
	[Event(name="complete", type="flash.events.Event")]
	
	public class ItunesLibraryParser extends Sprite implements IMediaParser
	{
		public var mpegAudioFileString:String = "MPEG audio file";
		private const FORMAT_NAME:String = "iTunes Music Library";
		
		private const MAC_STRING:String = "Mac OS";
	 	private const WINDOWS_STRING:String = "Windows";
		
		/*
		public static const PROTECTED_AAC_AUDIO_FILE:String = "Protected AAC audio file";
		public static const MPEG_AUDIO_STREAM:String = "MPEG audio stream";
		public static const PLAYLIST_URL:String = "Playlist URL";
		public static const AAC_AUDIO_FILE:String = "AAC audio file";
		*/

		[Bindable]
		public var media:ArrayCollection;
		
		private var currentIndex:Number = 0;
		private var totalCount:Number = 0;
		
		private var list:XMLList;
		
		public function ItunesLibraryParser():void
		{
		}
		
		public function get formatName():String
		{
			return FORMAT_NAME;
		}
		
		public function get defaultPath():String
		{
 			var os:String = Capabilities.os;
 			var out:String;
 			var appendPath:String;
 			
 			if(os.indexOf(MAC_STRING) > -1)
 			{
 				appendPath = "Music/iTunes/iTunes Music Library.xml";
 			}
 			else if (os.indexOf(WINDOWS_STRING) > -1)
 			{
 				appendPath = "My Documents/My Music/iTunes/iTunes Music Library.xml";
 			}
 			
 			if(appendPath != null)
 			{
 				var p:File = File.userDirectory.resolvePath(appendPath);
 				
 				if(p.exists)
 				{
 					out = p.nativePath;
 				}
 				else
 				{
 					out = File.userDirectory.nativePath;
 				}
 			}
 			else
 			{
 				out = File.userDirectory.nativePath;
 			}
 			
 			return out;
		}		
		
		private function trimNull(x:XML):String
		{
			if(x == null)
			{
				return "";
			}
			
			return String(x);
		}
		
		private function parseNode(dict:XML):Song
		{
			
			if(String(XMLUtil.getNextSibling(getKeyByName(dict, "Kind"))) !=
				 mpegAudioFileString)
			{
				return null;
			}
								
			var s:Song = new Song();
		
			s.artist = trimNull(XMLUtil.getNextSibling(getKeyByName(dict, "Artist")));
			s.title = trimNull(XMLUtil.getNextSibling(getKeyByName(dict, "Name")));
			s.path = trimTrailingSlash(String(XMLUtil.getNextSibling(getKeyByName(dict, "Location"))));
			s.track = int(XMLUtil.getNextSibling(getKeyByName(dict, "Track Number")));
			s.album = trimNull(XMLUtil.getNextSibling(getKeyByName(dict, "Album")));		
			s.bitRate = Number(XMLUtil.getNextSibling(getKeyByName(dict, "Bit Rate")));;
			
			//s.dateAdded;
			
			//s.dateModified;
			
			s.diskCount = int(XMLUtil.getNextSibling(getKeyByName(dict, "Disk Count")));;
			s.diskNumber = int(XMLUtil.getNextSibling(getKeyByName(dict, "Disk Number")));;
			s.genre = trimNull(XMLUtil.getNextSibling(getKeyByName(dict, "Genera")));;
			s.sampleRate = Number(XMLUtil.getNextSibling(getKeyByName(dict, "Sample Rate")));;
			s.size = Number(XMLUtil.getNextSibling(getKeyByName(dict, "Size")));;
			s.totalTime = Number(XMLUtil.getNextSibling(getKeyByName(dict, "Total Time")));;
			s.trackCount = int(XMLUtil.getNextSibling(getKeyByName(dict, "Track Count")));;
			s.trackCount = int(XMLUtil.getNextSibling(getKeyByName(dict, "Track Count")));;
			s.year = int(XMLUtil.getNextSibling(getKeyByName(dict, "Year")));;												

			return s;	
		}
		
		//needed for some versions of itunes
		private function trimTrailingSlash(s:String):String
		{
			if(s.charAt(s.length - 1) == "/")
			{
				return s.substring(0, s.length - 1);
			}
			
			return s;
		}
		
		private function parse(data:XML):void
		{
			var xml:XML = new XML(data);
			
			media = new ArrayCollection();
			
			list = xml.dict.dict.dict;
			currentIndex = 0;
			totalCount = list.length();
			addEventListener(Event.ENTER_FRAME, doParse);
		}
		
		private function doParse(event:Event):void
		{
			for(var i:int = 0; i < 100; i++)
			{
				if(currentIndex == list.length())
				{
					var c:ImportEvent = new ImportEvent(ImportEvent.DATA_PARSE_COMPLETE);
						c.statusMessage = "The MP3s from iTunes were Successfully imported";
					dispatchEvent(c);
					
					var d:ImportEvent = new ImportEvent(ImportEvent.IMPORT_COMPLETE);
						d.statusMessage = "The MP3s from iTunes were Successfully imported";
						d.media = media;
					dispatchEvent(d);					
					
					removeEventListener(Event.ENTER_FRAME, doParse);
					return;
				}
				
				var s:Song = parseNode(list[currentIndex]);
					
				if(s != null)
				{
					media.addItem(s);
				}
				
				currentIndex++;
			}
				
			var e:ImportProgressEvent = new ImportProgressEvent(ImportProgressEvent.PARSE_PROGRESS);
				e.bytesTotal = totalCount;
				e.bytesLoaded = currentIndex;
				e.statusMessage = "Importing MP3s from iTunes";
				
				dispatchEvent(e);	
				
				//trace(String((currentIndex/totalCount) * 100));
		}

		private function getKeyByName(dict:XML, name:String):XML
		{
			var xList:XMLList = dict.key.(text() == name);
			
			if(xList.length() == 0)
			{
				return null;
			}
			
			return xList[0];
		}
		
		public function loadData(path:String):void
		{
 			var fr:File = new File(path);
 			
 			if(!fr.exists)
 			{
 				//throw error
 			}
 			
 			var fileStream:FileStream = new FileStream();

 			fileStream.addEventListener(Event.COMPLETE, onFileReadComplete);
 			fileStream.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
 			fileStream.addEventListener(ProgressEvent.PROGRESS, onFileReadProgress);
 			fileStream.openAsync(fr, FileMode.READ);
		}

		
		private function onIOError(e:IOErrorEvent):void
		{
			dispatchEvent(e.clone());
		}

 		private function onFileReadProgress(e:ProgressEvent):void
 		{
 			var event:ImportProgressEvent = new ImportProgressEvent(ImportProgressEvent.LOAD_PROGRESS);
				event.bytesTotal = totalCount;
				event.bytesLoaded = currentIndex;
				event.statusMessage = "Loading iTunes Library";
				
				dispatchEvent(event);	 				
 		}		
		
 		private function onFileReadComplete(event:Event):void
 		{
 			var fs:FileStream = FileStream(event.target);
 			var data:String = fs.readUTFBytes(fs.bytesAvailable);
 			fs.close();
 			
			var x:XML;	
			var isValid:Boolean = true;
			
			//validate that the file is in the correct format
			try
			{			
				x = new XML(data);
				if(x.nodeKind() != XMLUtil.ELEMENT)
				{
					isValid = false;
				}
				
				if(x.localName() != "plist")
				{
					isValid = false;
				}
			}
			catch(e:Error)
			{
				isValid = false;
			}	
				
			if(!isValid)
			{
				var e:ImportParseErrorEvent = new ImportParseErrorEvent(ImportParseErrorEvent.INVALID_FORMAT_ERROR);
				dispatchEvent(e);
				return;
			}
			
 			parse(x);
 		}		
	}
}
